<!-- 添加推广链接 -->
<!-- 添加推广链接 -->
<template>
  <div>
    <el-dialog v-model="dialogVisible" alignCenter width="1080px" title="回传模板" draggable appendToBody destroyOnClose lockScroll :closeOnClickModal="false">
      <div style="width: 100%">
        <el-form ref="elFormRef" :validateOnRuleChange="false" :model="formData" scrollToError :rules="rules" style="width: 100%; min-height: 580px">
          <el-form-item label="模板名称" labelWidth="6em" prop="backTemplateName">
            <el-input v-model="formData.backTemplateName" maxlength="20" placeholder="请输入回传模版名称"></el-input>
          </el-form-item>
          <el-form-item label="上报方式" labelWidth="6em" prop="reportType">
            <box-from-border>
              <el-radio-group v-model="formData.reportType" style="display: flex; align-items: flex-start; justify-content: flex-start; margin: 10px 0">
                <div style="display: flex; flex: 1; flex-direction: column; align-items: flex-start; justify-content: flex-start">
                  <span style="font-size: 12px; color: var(--el-text-color-placeholder)">所有</span>
                  <el-radio label="回传用户的所有充值" :value="11"></el-radio>
                  <el-radio label="回传用户当天自然日的所有充值" :value="12"></el-radio>
                  <el-radio label="回传用户24小时内的所有充值" :value="13"></el-radio>
                </div>
                <div style="display: flex; flex: 1; flex-direction: column; align-items: flex-start; justify-content: flex-start; margin-left: 15px">
                  <span style="font-size: 12px; color: var(--el-text-color-placeholder)">首充</span>
                  <el-radio label="回传用户的首充" :value="21"></el-radio>
                  <el-radio label="回传用户当天自然日的首充" :value="22"></el-radio>
                  <el-radio label="回传用户24小时内的首充" :value="23"></el-radio>
                </div>
              </el-radio-group>
            </box-from-border>
          </el-form-item>
          <el-form-item label="支付模板" labelWidth="6em" prop="productTemplateId">
            <box-from-border @click="handleSelectTemplate()">
              <span v-if="formData.productTemplateId > 0" style="color: var(--el-input-text-color)">{{ productTemplateName }}</span>
              <span v-else style="color: var(--el-text-color-placeholder)">请选择支付模板</span>
            </box-from-border>
          </el-form-item>
          <div v-auto-animate style="margin-left: 6em">
            <div
              v-for="(item, index) in formData.productList"
              :key="item.productMarketingId"
              style="display: flex; flex-direction: row; place-items: center center; justify-content: center; margin-bottom: 18px"
            >
              <el-input disabled style="flex: 1.5" :modelValue="item._name"></el-input>
              <span style="margin-left: 6px">回传:</span>
              <el-form-item label="" labelWidth="6px" :prop="`productList.${index}.backMinNum`" :rules="rules.backMinNum" style="flex: 1; margin-bottom: 0">
                <base-input-number v-model="item.backMinNum" verify="add_int_or_zero" :min="0" :decimals="2" placeholder="请输入笔数"></base-input-number>
              </el-form-item>
              <span style="margin-left: 6px">笔后，按照每</span>
              <el-form-item
                label=""
                labelWidth="6px"
                :prop="`productList.${index}.backDenominatorNum`"
                :rules="rules.backDenominatorNum"
                style="flex: 1; margin-bottom: 0"
              >
                <base-input-number
                  v-model="item.backDenominatorNum"
                  verify="add_int_or_zero"
                  :min="0"
                  :decimals="0"
                  placeholder="请输入笔数"
                ></base-input-number>
              </el-form-item>
              <span style="margin-left: 6px">笔订单,前</span>
              <el-form-item
                label=""
                labelWidth="6px"
                :prop="`productList.${index}.backNumeratorNum`"
                :rules="rules.backNumeratorNum"
                style="flex: 1; margin-bottom: 0"
              >
                <base-input-number v-model="item.backNumeratorNum" verify="add_int_or_zero" :min="0" :decimals="0" placeholder="请输入笔数"></base-input-number>
              </el-form-item>
              <span style="margin-left: 6px">笔回传,余下{{ item.backDenominatorNum - item.backNumeratorNum }}笔不回传</span>
            </div>
          </div>
        </el-form>
        <el-button type="success" style="width: 100%" :loading="loading" :disabled="loading" @click="submit">提交</el-button>
      </div>
    </el-dialog>
    <page-select-template ref="pageSelectTemplateRef"></page-select-template>
  </div>
</template>

<script setup lang="ts">
  import { vAutoAnimate } from '@formkit/auto-animate/vue';
  import {
    type AddBackTemplateRequest,
    type BackTemplateProduct,
    type EditBackTemplateRequest,
    type PdtProductBackTemplateAggregation,
    type ReferralTemplate,
    addBackTemplateAxios,
    editBackTemplateAxios,
  } from '@/api/marketing-management';
  import PageSelectTemplate from '@/components/page/page-select-template/page-select-template.vue';
  import type { FormInstance, FormRules } from 'element-plus';

  type $EditShowData = {
    /** 操作 */
    action: 'edit';
    /** 模版 */
    template: PdtProductBackTemplateAggregation;
    /** 审核后的回调 */
    callBack?: () => void;
  };

  type $AddShowData = {
    /** 操作 */
    action: 'add';
    /** 审核后的回调 */
    callBack?: () => void;
  };
  type $ShowData = $AddShowData | $EditShowData;
  let callBack: $ShowData['callBack'] | undefined = undefined;

  const elFormRef: Ref<FormInstance | null> = ref(null);
  const pageLoad = shallowReactive<$PageLoad>({ loadState: true, description: '' });
  const dialogVisible = ref(false);
  const pageSelectTemplateRef: Ref<InstanceType<typeof PageSelectTemplate> | null> = ref(null);
  const loading = ref(false);
  const action = ref<'add' | 'edit'>('add');
  const productTemplateName = ref('');
  const formData = ref<AddBackTemplateRequest | EditBackTemplateRequest>({
    backTemplateName: '',
    productList: [],
    productTemplateId: -1,
    reportType: 11,
  });

  const rules = computed<FormRules>(() => {
    const _rules: FormRules = {
      backTemplateName: [{ required: true, type: 'string', message: '请输入模版名称', trigger: ['blur', 'change'] }],
      productList: [
        { required: true, type: 'number', message: `请选择位置`, trigger: ['blur', 'change'] },
        { required: true, type: 'enum', enum: [1, 2, 3], message: `位置不合法`, trigger: ['blur', 'change'] },
      ],
      reportType: [
        { required: true, type: 'number', message: `请选择上报类型`, trigger: ['blur', 'change'] },
        { required: true, type: 'enum', enum: [22, 11, 12, 13, 21, 23], message: `上报类型不合法`, trigger: ['blur', 'change'] },
      ],
      backMinNum: [
        { required: true, type: 'number', message: `请输入笔数`, trigger: ['blur', 'change'] },
        { required: true, type: 'integer', min: 0, message: `笔数不合法`, trigger: ['blur', 'change'] },
      ],
      backDenominatorNum: [
        { required: true, type: 'number', message: `请输入比例`, trigger: ['blur', 'change'] },
        { required: true, type: 'integer', min: 0, message: `比例不合法`, trigger: ['blur', 'change'] },
      ],
      backNumeratorNum: [
        { required: true, type: 'number', message: `请输入比例`, trigger: ['blur', 'change'] },
        { required: true, type: 'integer', min: 0, message: `比例不合法`, trigger: ['blur', 'change'] },
      ],
    };
    return _rules;
  });

  /**
   * 选择模板
   * @param type - 类型
   */
  function handleSelectTemplate() {
    pageSelectTemplateRef.value?.show({
      templateType: 4,
      selectCallBack(res: ReferralTemplate) {
        productTemplateName.value = res.templateName;
        formData.value.productTemplateId = res.productTemplateId!;
        formData.value.productList = res.productList.map((item) => {
          const newItem: BackTemplateProduct = {
            backMinNum: 0,
            backNumeratorNum: 1,
            backDenominatorNum: 1,
            backRate: 100,
            productId: item.productId! as number,
            // productMarketingId: item.productMarketingId!,
            _name: `¥${item.productPrice} -- ${item.productName}`,
          };
          return newItem;
        });
      },
    });
  }

  /**
   * 提交
   */
  async function submit() {
    try {
      formData.value.productList.forEach((item) => {
        item.backRate = Math.round((item.backNumeratorNum / item.backDenominatorNum) * 10000) / 100;
      });
      await elFormRef.value?.validate();
      try {
        loading.value = true;
        if (action.value === 'edit') {
          await editBackTemplateAxios(formData.value as EditBackTemplateRequest);
        } else {
          await addBackTemplateAxios(formData.value);
        }

        loading.value = false;
        typeof callBack === 'function' && callBack();
        hide();
      } catch (error) {
        loading.value = false;
        ElToast.error(error.msg || '提交失败，-BD001');
      }
    } catch (error) {
      ElToast.error('提交失败，请完善表单，-BD002');
    }
  }

  /**
   * 显示
   */
  function show(data: $ShowData) {
    dialogVisible.value = true;
    callBack = data.callBack;
    pageLoad.loadState = false;
    action.value = data.action;
    if (data.action === 'edit') {
      productTemplateName.value = data.template.templateName;
      data.template.backSettingList.forEach((item) => {
        item._name = `¥${item.productPrice} -- ${item.productName}`;
      });
      formData.value = {
        backTemplateName: data.template.backTemplateName,
        productList: data.template.backSettingList,
        productTemplateId: data.template.productTemplateId!,
        reportType: data.template.reportType,
        productBackTemplateId: data.template.productBackTemplateId,
      };
    } else {
      productTemplateName.value = '';
      formData.value = {
        backTemplateName: '',
        productList: [],
        productTemplateId: -1,
        reportType: 11,
      };
    }
  }

  /**
   * 隐藏
   */
  function hide() {
    dialogVisible.value = false;
  }

  defineExpose({ show, hide });
</script>

<style scoped lang="scss">
  .content-vessel {
    display: grid;
    grid-template-columns: repeat(auto-fill, 259px);
    gap: 15px;
    place-content: center;
    width: 100%;
    padding-bottom: 15px;

    .content-box {
      overflow: hidden;
      cursor: pointer;
      background: $c-bg-block;
      border-radius: 10px;
      box-shadow: var(--my-box-shadow-fill);

      .title-box {
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-around;
        width: 100%;
        padding: 10px 0;
      }
    }
  }
</style>
